// Sunghan Cho
// 301140084
// sunghanc@sfu.ca

#include "uiitemtablewidget.h"
#include "ui_uiitemtablewidget.h"
#include "itemlistmodel.h"

#include <QDebug>
#include <QTableWidget>


UiItemTableWidget::UiItemTableWidget(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::UiItemTableWidget)
{
	m_pModel = 0;
	ui->setupUi(this);

	ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tableView->setSortingEnabled(false);

	QObject::connect(ui->btnClearSelection, SIGNAL(clicked()),
					 this, SLOT(clearAllSelections()));

}

UiItemTableWidget::~UiItemTableWidget()
{
	delete ui;
}

void UiItemTableWidget::clearAllSelections()
{
	ui->tableView->clearSelection();
}

void UiItemTableWidget::setModel(ItemListModel *pModel)
{
	m_pModel = pModel;

	// Setting the model for the table clears the selection model, and hence any signal-slot bindings.
	ui->tableView->setModel(pModel);

	// Register for change in selection events.
	// The selection changes occur when the user clears the selection, as well as selecting with the mouse.
	// The clicked is needed because if the two student tables each have a different student selected,
	// then re-clicking on one of them will not trigger a selection change. Hence, monitor clicks.
	// Transmitting multiple events is not a problem: the received just gets multiple updates.
	QObject::connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
					 this, SLOT(tableSelectionChanged(QItemSelection)));
	QObject::connect(ui->tableView, SIGNAL(clicked(QModelIndex)),
					 this, SLOT(tableClicked(QModelIndex)));

	// Register for the layoutChanged signal, so we can correct a problem with
	// the last column not rescalling.
	QObject::connect(pModel, SIGNAL(layoutChanged()),
					 this, SLOT(redrawColumns()));
}

void UiItemTableWidget::tableSelectionChanged(QItemSelection selected)
{
	int itemIndex = INVALID_SELECTION;
	if (selected.length()) {
		itemIndex = selected.first().top();
	}

	m_pModel->setSelectedItem(itemIndex);
}

void UiItemTableWidget::tableClicked(QModelIndex selected)
{
	m_pModel->setSelectedItem(selected.row());
}

void UiItemTableWidget::redrawColumns()
{
	// Reset the stertch-last-column flag to force the last column to update.
	// Seems to be a bug in Qt.
	ui->tableView->resizeColumnsToContents();
	ui->tableView->horizontalHeader()->setStretchLastSection(true);
}

void UiItemTableWidget::setDescription(QString description)
{
	ui->lblDescription->setText(description);
}
